import { getDefaultImageFormatStyle } from "@/logics/shortcutkey";

function getStrFileSize(size) {
  if (!size) return "";

  var num = 1024.0; //byte

  if (size < num) return size + "B";
  if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + "K"; //kb
  if (size < Math.pow(num, 3))
    return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
  if (size < Math.pow(num, 4))
    return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
  return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
}

function urlToBase64UseImage(url, format) {
  return new Promise((resolve, reject) => {
    var image = new Image();
    image.onload = function () {
      console.log("onload");
      var canvas = document.createElement("canvas");
      canvas.width = this.naturalWidth;
      canvas.height = this.naturalHeight;
      // 将图片插入画布并开始绘制
      canvas.getContext("2d").drawImage(image, 0, 0);
      // result
      var result = canvas.toDataURL(format);
      resolve(result);
    };
    // CORS 策略，会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
    image.setAttribute("crossOrigin", "Anonymous");
    image.src = url;
    // 图片加载失败的错误处理
    image.onerror = function (ex) {
      console.error(ex);
      reject(ex);
    };
  });
}

function isImageURL(url) {
  var imageRegex =
    /(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:bmp|jpe?g|png|svg))(?:\?([^#]*))?(?:#(.*))?/i;

  //to exclude .gif
  return (
    (url.indexOf("data:image") === 0 && url.indexOf("data:image/gif") !== 0) ||
    imageRegex.test(url)
  );
}

function isGif(url) {
  var imageRegex =
    /(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:gif|webp))(?:\?([^#]*))?(?:#(.*))?/i;
  return url.indexOf("data:image/gif") === 0 || imageRegex.test(url);
}

function isBase64(str) {
  if (str === "" || str.trim() === "") {
    return false;
  }
  if (str.indexOf("data:") != -1 && str.indexOf("base64") != -1) {
    return true;
  } else {
    return false;
  }
}

export function toDataUrlAsync(url) {
  return new Promise(async (resolve, reject) => {
    try {
      await toDataURL(url, resolve, reject);
    } catch (ex) {
      console.error(ex);
      reject(ex);
    }
  });
}
async function toDataURL(url, callback, reject) {
  if (isBase64(url)) {
    console.log("图片已经是base64");
    callback(url);
    return;
  }
  var cacheMaxImageSize = 1024 * 1024;
  if (isImageURL(url)) {
    let format = "image/" + (await getDefaultImageFormatStyle());
    let res;
    res = await urlToBase64UseImage(url, format)
      .catch(() => {
        //可能是因为存在缓存导致的跨域问题
        if (url.indexOf("?") === -1) {
          const newUrl = url + "?__sct=" + new Date().getTime();
          return urlToBase64UseImage(newUrl, format);
        } else {
          const newUrl = url + "&__sct=" + new Date().getTime();
          return urlToBase64UseImage(newUrl, format);
        }
      })
      .catch(() => {
        //使用接口尝试一次，大概率还是要跨域
        return toDataURLUseAjax(url, resolve, reject);
      });

    if (res.indexOf("data:image") === -1) {
      throw "请重新选择图片";
    }

    if (res.length >= cacheMaxImageSize) {
      throw "超过最大尺寸" + res.length;
      // hideLoading();
      // showMessages(
      //   i18n_words.messasge["file_too_large"] +
      //     "(" +
      //     getStrFileSize(res.length) +
      //     "), " +
      //     i18n_words.messasge["upload_other_ways"]
      // );
    } else {
      callback(res);
    }
  } else if (isGif(url)) {
    throw "暂不支持gif";
    console.log("is gif", url, currentTab);

    chrome.tabs.sendMessage(
      currentTab.id,
      { action: "get-gif", url: url },
      function (response) {
        if (response === "ok" || response.error) {
          console.log("not yet read the gif base64 data");
          // hideLoading();
          // showMessages(i18n_words.messasge["fail_to_get_gif"]);
        } else {
          callback(response);
        }
      }
    );
  } else {
    toDataURLUseAjax(url, callback, reject);
  }
}

function toDataURLUseAjax(url, callback, reject) {
  var xhr = new XMLHttpRequest();
  var timeout;
  var sent = false;
  var isVideo =
    url.toLowerCase().indexOf(".mp4") > -1 ||
    url.toLowerCase().indexOf(".webm") > -1;
  var isGIF = url.toLowerCase().indexOf(".gif") > -1;
  if (isGIF) {
    xhr.timeout = 60000;
  } else {
    xhr.timeout = 30000;
  }
  if (isVideo) {
    callback(undefined);
    return;
  }
  xhr.onload = function () {
    console.log("onload....");
    clearTimeout(timeout);
    var reader = new FileReader();
    reader.onloadend = function () {
      console.log("onloadend....");
      if (!sent) {
        sent = true;
        if (
          reader.result.indexOf("data:image") > -1 ||
          reader.result.indexOf("data:text/xml") > -1
        ) {
          if (reader.result.length >= cacheMaxImageSize) {
            throw "超过最大尺寸" + reader.result.length;
            // hideLoading();
            // showMessages(
            //   i18n_words.messasge["file_too_large"] +
            //     "(" +
            //     getStrFileSize(reader.result.length) +
            //     "), " +
            //     i18n_words.messasge["upload_other_ways"]
            // );
          } else {
            callback(reader.result);
          }
        } else {
          throw "请重新选择图片";
          // hideLoading();
          // showMessages(i18n_words.messasge["select_image_url"]);
        }
      }
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.onerror = function (ex) {
    reject(ex);
  };
  xhr.ontimeout = function (e) {
    // hideLoading();
    // showMessages("Save image failed, open the url and pin it again please.");
  };
  xhr.withCredentials = true;
  xhr.open("GET", url, true);
  xhr.setRequestHeader("Cache-Control", "no-cache");
  xhr.responseType = "blob";
  xhr.send();
}
